<template>
  <view class="page">
    <up-sticky bgColor="#fff">
      <up-tabs
        :list="$data.tabs"
        :scrollable="true"
        :lineColor="`${BasicConfig.MainColor}`"
        :current="$data.tabCurrent"
        @click="onClickTab"
      ></up-tabs>
    </up-sticky>
    <view class="padding">
      <ListOrder ref="RefData" @action="onAction" @clickItem="onDetail" />
    </view>
    <PopupCSPhone v-model:show="$data.csphoneShow" title="官方客服电话" />
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick } from "vue";
import {
  onLoad,
  onShow,
  onReady,
  onReachBottom,
  onPullDownRefresh,
} from "@dcloudio/uni-app";
import BasicConfig from "../../../utils/config";
import ListOrder from "./components/ListOrder.vue";
import {
  hotelOrderAfterSaleStatus,
  orderActionEnum,
  orderSourceType,
  orderStatus,
  searchOrderStatus,
} from "../../../enums/order";
import { cancelOrder, getOrderDetail } from "../../../api/Interface/order";
import errorCode from "../../../utils/http/errorCode";
import { jumpPage } from "../../../utils/route/route";
import { usePayment } from "../../../hooks/usePay";
import { useSubscribeTemplate } from "../../../hooks/useSubscribe";
import { subscribeEnum } from "../../../enums/subscribe";
import PopupCSPhone from "../../../components/PopupCSPhone.vue";
import { goodsType, reservaSwitch } from "../../../enums/goods";
const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  tabs: [
    { value: null, name: "全部" },
    { value: searchOrderStatus.awaitPay, name: "待支付" },
    { value: searchOrderStatus.awaitReservation, name: "待预约" },
    { value: searchOrderStatus.awaitService, name: "待服务" },
    { value: searchOrderStatus.awaitConfirm, name: "待确认" },
    // { value: searchOrderStatus.awaitComment, name: "待评价" },
    { value: searchOrderStatus.afterSales, name: "售后" },
  ],
  tabCurrent: 0,
  loadNum: 0, // 抖音小程序奇葩bug 首次加载会自动触发一次点击事件...???wtf
  csphoneShow: false,
  orderInfo: null,
});
const searchObj = reactive({
  page: 1,
  limit: 20,
  statusType: null,
});
const onClickTab = (item, index) => {
  searchObj.statusType = item.value;
  $data.tabCurrent = index;
  fnGetDatas($vm.$ListLoadEnum.load);
  // $data.loadNum = 1;
};
const onAction = (item, btn) => {
  // console.log("$data.loadNum~~~3", $data.loadNum);
  // if ($data.loadNum <= 1) {
  //   $data.loadNum++;
  //   return;
  // }
  const { key } = btn;
  console.log("onAction key", key);
  const { localNo, serviceSnapshot, domesticServiceStatus, orderServiceId } =
    item;
  console.log("onAction", item, localNo);
  const service = JSON.parse(serviceSnapshot);
  switch (key) {
    // 取消订单
    case orderActionEnum.cancel:
      jumpPage({
        to: "/package-service/pages/order/details/cancel",
        query: {
          localNo,
        },
      });
      break;
    // 重新下单
    case orderActionEnum.reset:
      if (domesticServiceStatus == 0) {
        BasicConfig.toast("服务已下架");
        return;
      }
      jumpPage({
        to: "/package-service/pages/index",
        query: {
          id: service.domesticServiceId,
        },
      });
      break;
    // 支付
    case orderActionEnum.pay:
      // usePayment({ localNo, type: orderSourceType.daily }, "wechat").then(
      //   async (res) => {
      //     BasicConfig.toast(res.msg);
      //     if (res.code === errorCode.success) {
      //       const ids = [
      //         subscribeEnum.hotel.workerTake,
      //         subscribeEnum.hotel.orderStart,
      //         subscribeEnum.hotel.orderAwaitConfirm,
      //         // subscribeEnum.hotel.orderComment,
      //       ];
      //       try {
      //         await useSubscribeTemplate(ids);
      //       } catch (e) {
      //         console.log("useSubscribeTemplate err", e);
      //       }
      //       setTimeout(() => {
      //         fnGetDatas($vm.$ListLoadEnum.load);
      //       }, 1500);
      //     }
      //   }
      // );
      BasicConfig.loadToast("调起支付...");
      try {
        console.log("continueToPay", tt.continueToPay());
        console.log("tt", tt);
        console.log("uni", uni);
        tt.continueToPay({
          outOrderNo: localNo,
          success(res) {
            console.log("continueToPay res", res);
            setTimeout(() => {
              fnGetDatas($vm.$ListLoadEnum.load);
            }, 10);
          },
          fail(err) {
            console.log("continueToPay err", err);
            if (err.errMsg.includes("payment is cancelled")) {
            } else {
              uni.showModal({
                content: "支付失败，请联系管理员！",
                showCancel: false,
                confirmText: "知道了",
                cancelColor: BasicConfig.MainColor,
              });
            }
          },
          complete() {
            uni.hideLoading();
          },
        });
      } catch (e) {
        uni.hideLoading();
      }
      break;
    // 评论
    case orderActionEnum.comment:
      // jumpPage({
      //   to: "/package-service/pages/order/details/awaitComment",
      //   query: {
      //     localNo,
      //     orderServiceId,
      //   },
      // });
      break;
    // 再来一单
    case orderActionEnum.again:
      if (domesticServiceStatus == 0) {
        BasicConfig.toast("服务已下架");
        return;
      }
      jumpPage({
        to: "/package-service/pages/index",
        query: {
          id: service.domesticServiceId,
        },
      });
      break;
    // 客服热线
    case orderActionEnum.custom:
      $data.csphoneShow = true;
      break;
    // 预约
    case orderActionEnum.reservation:
      jumpPage({
        to: "/package-service/pages/order/confirm",
        query: {
          localNo,
          orderServiceId,
          id: service.domesticServiceId,
        },
      });
      break;
    // 申请退款
    case orderActionEnum.refund:
      jumpPage({
        to: "/package-service/pages/order/afterSales/apply",
        query: {
          localNo,
          orderServiceId,
        },
      });
      break;
    default:
      break;
  }
};
const onDetail = async (e) => {
  const { status, orderServiceId, firstAfterSaleStatus } = e;
  console.log("onDetail", e, e.localNo);
  if (firstAfterSaleStatus == hotelOrderAfterSaleStatus.allEnd) {
    // return;
    await getOrderData(e.localNo, orderServiceId);
  } else if (firstAfterSaleStatus == hotelOrderAfterSaleStatus.parting) {
    await getOrderData(e.localNo, orderServiceId);
  } else if (firstAfterSaleStatus == hotelOrderAfterSaleStatus.alling) {
    await getOrderData(e.localNo, orderServiceId);
  } else if (status == orderStatus.awaitPay) {
    jumpPage({
      to: "/package-service/pages/order/detail",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  } else if (status == orderStatus.finding) {
    jumpPage({
      to: "/package-service/pages/order/details/finding",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  } else if (status == orderStatus.awaitService) {
    jumpPage({
      to: "/package-service/pages/order/details/awaitService",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  } else if (status == orderStatus.awaitConfirm) {
    jumpPage({
      to: "/package-service/pages/order/details/awaitConfirm",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  } else if (status == orderStatus.awaitComment) {
    // jumpPage({
    //   to: "/package-service/pages/order/details/awaitComment",
    //   query: {
    //     localNo: e.localNo,
    //   },
    // });
    jumpPage({
      to: "/package-service/pages/order/details/final",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  } else if (status == orderStatus.final) {
    jumpPage({
      to: "/package-service/pages/order/details/final",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  } else if (status == orderStatus.serving) {
    jumpPage({
      to: "/package-service/pages/order/details/serving",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  } else if (status == orderStatus.awaitReservation) {
    jumpPage({
      to: "/package-service/pages/order/details/awaitReservation",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  } else if (status == orderStatus.cancel) {
    jumpPage({
      to: "/package-service/pages/order/detail",
      query: {
        localNo: e.localNo,
        orderServiceId,
      },
    });
  }
};
const getOrderData = async (localNo, orderServiceId) => {
  console.log("退单商品开始识别~~~~~~");
  await getOrderDetail({
    localNo,
    orderServiceId,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.orderInfo = res.data;
      if ($data.orderInfo) {
        const { dyGoodsType, status, refundSwitch } = $data.orderInfo;
        if (
          dyGoodsType == goodsType.reservation &&
          refundSwitch == reservaSwitch.on &&
          Number(status) > orderStatus.awaitReservation
        ) {
          console.log("预约品,进入apply~~~~~~~~~");
          jumpPage({
            to: `/package-service/pages/order/afterSales/apply`,
            query: {
              localNo,
              orderServiceId,
            },
          });
        } else {
          jumpPage({
            to: `/package-service/pages/order/afterSales/apply`,
            query: {
              localNo,
              orderServiceId,
            },
          });
          // console.log("进入detail~~~~~~~~~");
          // jumpPage({
          //   to: `/package-service/pages/order/afterSales/detail`,
          //   query: {
          //     localNo,
          //     orderServiceId,
          //   },
          // });
        }
      }
    }
  });
};
onLoad((options) => {
  if (options.status) {
    searchObj.statusType = options.status;
    const index = $data.tabs.findIndex((t) => t.value == searchObj.statusType);
    $data.tabCurrent = index >= 0 ? index : 0;
  }
});
onShow(() => {
  setTimeout(() => {
    fnGetDatas($vm.$ListLoadEnum.load);
    // $data.loadNum++;
    // console.log("$data.loadNum~~~1", $data.loadNum);
  }, 500);
});
const RefData = ref();
/** 获取数据列表 */
const fnGetDatas = (type = $vm.$ListLoadEnum.load) => {
  RefData.value.loadDatas(type, searchObj);
};
onReady(() => {});
/** 下滑加载 */
onReachBottom(() => {
  fnGetDatas($vm.$ListLoadEnum.bottom);
});
/** 下拉刷新 */
onPullDownRefresh(() => {
  fnGetDatas($vm.$ListLoadEnum.load);
});
</script>

<style lang="scss" scoped>
.page {
  background: #f7f8fa;
  width: 100vw;
  min-height: 100vh;
  padding-bottom: 300rpx;
}
</style>
